package com.ask.controller.admin;

import com.ask.constant.JwtClaimsConstant;
import com.ask.context.BaseContext;
import com.ask.dto.EmployeeDTO;
import com.ask.dto.EmployeePageQueryDTO;
import com.ask.dto.EmployeeLoginDTO;
import com.ask.dto.PasswordEditDTO;
import com.ask.entity.Employee;
import com.ask.properties.JwtProperties;
import com.ask.result.PageResult;
import com.ask.result.Result;
import com.ask.service.EmployeeService;
import com.ask.utils.JwtUtil;
import com.ask.vo.EmployeeLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin/employee")
@Slf4j
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // --------------正式代码段---------------- //

    /**
     * 新增员工
     *
     * @param employeeDTO
     * @return
     */
    @PostMapping
    public Result<Employee> save(@RequestBody EmployeeDTO employeeDTO) {
        log.info("add employee: {}", employeeDTO);
        employeeService.save(employeeDTO);
        return Result.success();
    }

    /**
     * 跟新员工信息
     *
     * @param employeeDTO
     * @return
     */
    @PutMapping
    public Result update(@RequestBody EmployeeDTO employeeDTO) {
        log.info("update employee : {}", employeeDTO);
        employeeService.update(employeeDTO);
        return Result.success();
    }

    /**
     * 根据id获取单条记录
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Employee> getById(@PathVariable Long id) {
        log.info("enter method getById : {}", id);
        return Result.success(employeeService.getById(id));
    }

    /**
     * 启用/禁用员工账号
     *
     * @param id
     * @return
     */
    @PutMapping("/status/{status}")
    public Result startorStop(@PathVariable Integer status, Long id) {
        log.info("启用/禁用员工账号，id :{}", id);
        employeeService.startorStop(status, id);
        return Result.success();
    }


    /**
     * 修改密码
     *
     * @param passwordEditDTO
     * @return
     */
    @PutMapping("/editPassword")
    public Result editPassword(@RequestBody PasswordEditDTO passwordEditDTO) {
        employeeService.editPassword(passwordEditDTO);
        return Result.success();
    }

    /**
     * 分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @GetMapping("/page")
    public Result<PageResult> page(@ModelAttribute EmployeePageQueryDTO employeePageQueryDTO) {
        PageResult result = employeeService.pageQuery(employeePageQueryDTO);
        return Result.success(result);
    }

    /**
     * 用户登录
     *
     * @param loginDTO
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody EmployeeLoginDTO loginDTO, HttpServletResponse response) {
        // 1. 用户登录
        Employee employee = employeeService.login(loginDTO);
        // 2. token生成
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());

        // 生成短期有效的JWT
        String accessToken = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        // 生成长期有效的token，存储至redis（ttl为30天）
        String refreshToken = JwtUtil.createJWT(
                jwtProperties.getRefreshSecretKey(),
                jwtProperties.getRefreshTtl(),
                claims
        );

        stringRedisTemplate.opsForValue().set(
                accessToken,
                refreshToken,
                30,
                TimeUnit.DAYS
        );


        // 3. 封装vo对象返回前端;
        Map<String, String> map = new HashMap<>();
        map.put(jwtProperties.getAccessTokenName(), accessToken);
//        EmployeeLoginVO loginVO = EmployeeLoginVO.builder()
//                .id(employee.getId())
//                .name(employee.getName())
//                .userName(employee.getUsername())
//                .token(accessToken)
//                .build();
        return Result.success(map);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @PostMapping("/logout")
    public Result logout() {
        BaseContext.removeCurrentId();
        return Result.success();
    }

    @PostMapping("/login1")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        return Result.success(employeeLoginVO);
    }
}